#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import time
from xlrd  import open_workbook
from PyQt4 import QtCore, QtGui
from rpy   import *
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfgen   import canvas

from rGuiMinder       import Ui_RGuiMinder
from rGuiLinearRegression import Ui_Regression
from rGuiImportData   import Ui_ImportDataWidget
from rGuiImportLabels import Ui_ImportColorLabels
from rGuiSubset       import Ui_SubsetStadistics
from initialLoad      import Ui_Dialog
from reportlab.lib.utils import ImageReader


class rData:
    def __init__(self):
        self.variables = []
        self.varParams = []
        self.parameters  = []
        self.paramValues = []
        self.labels = []
        self.labelsValues = []
        self.values = []

    def getParams(self):
        params = []
        for i in self.varParams:
            for j in i:
                print j
                if (params.count(j) == 0):
                    params.append(j)
        return params

    def addParam(self, pName, pValues):
        if (self.parameters.count(pName) == 0):
            self.parameters.append(pName)
            self.paramValues.append(pValues)
            self.labels.append([])
            self.labelsValues.append([])

    def addLabel(self, pName, lName, lValues):
        index = self.parameters.index(pName)
        self.labels[index].append(lName)
        self.labelsValues[index].append(lValues)

class playThread(QtCore.QThread):
    def __init__(self, f, r, a):
        self.frame  = f
        self.rate   = r
        self.action = a
        self.state  = 1
        QtCore.QThread.__init__(self)
 
    def run(self):

        while (self.state == 1):
            if (self.action == "forward"):
                self.frame += 1
                if (self.frame == self.rate):
                    self.frame = 0
                self.emit( QtCore.SIGNAL('update(int)'),  self.frame)
                time.sleep(0.3)
            if (self.action == "backward"):
                self.frame -= 1
                if (self.frame == 0):
                    self.frame = self.rate
                self.emit( QtCore.SIGNAL('update(int)'),  self.frame)
                time.sleep(0.3)
        self.terminate()

class subsetWidget(QtGui.QDialog, Ui_SubsetStadistics):
    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.data = rData()
        self.param = 0
        self.paramVal = 0 
        self.canvasS = QtGui.QPixmap(400, 400)
        self.canvasS.fill()
        self.canvasSub.setPixmap(self.canvasS)
        self.logCanvas = None
        self.logBool = False


    def splitVariable(self):

        workingData = []
        index1 = self.categorical.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index1]:
                workingData.append(i[self.paramVal + 1])
            del workingData[0]
        else:
            workingData = self.data.values[index1][self.paramVal + 1]
            del workingData[0]


        self.variableStats.clearContents()
        for i in range(self.variableStats.rowCount()):
                self.variableStats.removeRow(0)
        n = self.parts1.value()
        r.assign('n',n)
        r.assign('x',workingData)
        r('f=cut(x, breaks=quantile(x,seq(0,1,1/n)), include.lowest = TRUE, labels=paste(\'Q\',1:n,sep='') )')
        r('s=by(x,f,summary)')
        for i in range(n):
            self.variableStats.insertRow(self.variableStats.rowCount())
            self.variableStats.setItem(i,0,QtGui.QTableWidgetItem(str(i)))
            for j in range(6):
                r.assign('i', i + 1)
                r.assign('j', j + 1)
                val = r('s[[i]][[j]]')
                self.variableStats.setItem(i,j,QtGui.QTableWidgetItem(str(val)))
            r.assign('i', i + 1)
            r('x_sub <- x[f[] == levels(f)[i]]')
            self.variableStats.setItem(i,6,QtGui.QTableWidgetItem(str(r('sd(x_sub)'))))
            self.variableStats.setItem(i,7,QtGui.QTableWidgetItem(str(r('length(x_sub)'))))
        self.variableStats.resizeColumnsToContents()
        self.variableStats.resizeRowsToContents()
        self.selected1.setMaximum(self.parts1.value())
        self.selected1.setValue(1)
        self.variableStats.selectRow(0)
        self.splitVariable2()

    def splitVariable2(self):

        subset = self.selected1.value()
        workingData = []
        index = self.noCategorical.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index]:
                workingData.append(i[self.paramVal + 1])
            del workingData[0]
        else:
            workingData = self.data.values[index][self.paramVal + 1]
            del workingData[0]

        r.assign('y',workingData)
        r.assign('ytotal',workingData)

        r.assign('index',subset)
        r('y <- y[f[] == levels(f)[index]]')

        self.variable2Stats.clearContents()
        for i in range(self.variable2Stats.rowCount()):
                self.variable2Stats.removeRow(0)

        n = self.parts2.value()
        r.assign('m',n)

        r('g=cut(y, breaks=quantile(y,seq(0,1,1/m)), include.lowest = TRUE, labels=paste(\'Q\',1:m,sep='') )')
        r('r=by(y,g,summary)')

        for i in range(n):
            self.variable2Stats.insertRow(self.variable2Stats.rowCount())
            self.variable2Stats.setItem(i,0,QtGui.QTableWidgetItem(str(i)))
            for j in range(6):
                r.assign('i', i + 1)
                r.assign('j', j + 1)
                val = r('r[[i]][[j]]')
                self.variable2Stats.setItem(i,j,QtGui.QTableWidgetItem(str(val)))
            r.assign('i', i + 1)
            r('y_sub <- y[g[] == levels(g)[i]]')
            self.variable2Stats.setItem(i,6,QtGui.QTableWidgetItem(str(r('sd(y_sub)'))))
            self.variable2Stats.setItem(i,7,QtGui.QTableWidgetItem(str(r('length(y_sub)'))))
        self.variableStats.resizeColumnsToContents()
        self.variableStats.resizeRowsToContents()
        self.selected2.setMaximum(self.parts2.value())
        self.selected2.setValue(1)
        self.variable2Stats.selectRow(0)
        self.plot()

    def selectRow(self, row, col):
        self.selected1.setValue(row + 1)
        self.variableStats.selectRow(row)

    def selectRow2(self, row, col):
        self.selected2.setValue(row + 1)
        self.variable2Stats.selectRow(row)

    def selectGroup(self, index):
        self.variableStats.selectRow(index - 1)
        self.splitVariable2()

    def selectGroup2(self, index):
        self.variable2Stats.selectRow(index - 1)

    def closeWindow(self):
        self.reject()

    def plot(self):
        if (self.boxplotButton.isChecked()):
            self.boxPlot()
        if (self.radioHist.isChecked()):
            self.histogram()

    def boxPlot(self):
        if ~self.plot1.isChecked():
           subset = self.selected1.value()
           r.assign('index',subset)
           r('z <- x[f[] == levels(f)[index]]')
           r.png("box.png", 400, 400)
           r('boxplot(z)')
           r.dev_off()
           self.canvasS.load("box.png")
           self.canvasSub.setPixmap(self.canvasS.scaled(400, 400))

	   """
		Save Log file
	   """

	   if self.logBool:
		  print "EL LOG ESTA ACTIVADO SUBSET"
		  im = ImageReader("box.png")
                  self.logCanvas.drawString(100,500,"Subset Boxplot Created")
		  self.logCanvas.drawImage(im,100,100)
		  self.logCanvas.showPage()
	   else:
		  print "EL LOG ESTA DESACTIVADO"


           
        else:
           index2 = self.selected2.value()
           r.assign('indice2',index2)
           r('z <- y[g[] == levels(g)[indice2]]')
           r.png("box.png", 400, 400)
           r('boxplot(z)')
           r.dev_off()
           self.canvasS.load("box.png")
           self.canvasSub.setPixmap(self.canvasS.scaled(400, 400))

	   """
		Save Log file
	   """

	   if self.logBool:
		  print "EL LOG ESTA ACTIVADO SUBSET"
		  ima = ImageReader("box.png")
                  self.logCanvas.drawString(100,500,"Subset Boxplot Created")
		  self.logCanvas.drawImage(ima,100,100)
		  self.logCanvas.showPage()
	   else:
		  print "EL LOG ESTA DESACTIVADO"


    def bars(self):
	meansVector = []
	labels = []
	for i in range(self.parts1.value()):
           r.assign('index',i+1)
           hola1 = r('z1 <- x[f[] == levels(f)[index]]')
           hola2 = r('z2 <- y[f[] == levels(f)[index]]')
           hola3 = r('z <- ytotal[f[] == levels(f)[index]]')
	   print "X"
	   xx = r('x')
	   print xx
	   print "X Tamaño"
           l1 = r('lx <- length(x)')
	   print l1
	   print "Y"
	   yy = r('y')
	   print yy
	   print "Y Tamaño"
           l2 = r('ly <- length(y)')
	   print l2
	   print "Tamaño F"
           l3 = r('lf <- length(f)')
           print l3
	   print "X con filtro"
	   print hola1
	   print "Y con filtro"
	   print hola2
	   meansVector.append(r('mean(z)'))
	   labels.append(str(i+1))

	print "MEAN VECTOR"
	print meansVector
	r.png("bar.png", 400, 400)
        r.assign('m',meansVector)
        r.assign('l',labels)
	r('barplot(m,names.arg=l)')
	r.dev_off()
	self.canvasS.load("bar.png")
	self.canvasSub.setPixmap(self.canvasS.scaled(400, 400))

	"""
	Save Log file
	"""

	if self.logBool:
	   print "EL LOG ESTA ACTIVADO SUBSET"
	   im = ImageReader("bar.png")
           self.logCanvas.drawString(100,500,"Subset Barplot Created")
	   self.logCanvas.drawImage(im,100,100)
	   self.logCanvas.showPage()
	else:
	   print "EL LOG ESTA DESACTIVADO"


    def histogram(self):
        if ~self.plot1.isChecked():
           subset = self.selected1.value()
           r.assign('index',subset)
           r('z <- x[f[] == levels(f)[index]]')
           r.png("hist.png", 400, 400)
           r('hist(z)')
           r.dev_off()
           self.canvasS.load("hist.png")
           self.canvasSub.setPixmap(self.canvasS.scaled(400, 400))

	   """
		Save Log file
	   """

	   if self.logBool:
		  print "EL LOG ESTA ACTIVADO SUBSET"
		  im = ImageReader("hist.png")
                  self.logCanvas.drawString(100,500,"Subset Histogram Created")
		  self.logCanvas.drawImage(im,100,100)
		  self.logCanvas.showPage()
	   else:
		  print "EL LOG ESTA DESACTIVADO"

           
        else:
           index2 = self.selected2.value()
           r.assign('indice2',index2)
           r('z <- y[g[] == levels(g)[indice2]]')
           r.png("hist.png", 400, 400)
           r('hist(z)')
           r.dev_off()
           self.canvasS.load("hist.png")
           self.canvasSub.setPixmap(self.canvasS.scaled(400, 400))

	   """
		Save Log file
	   """

	   if self.logBool:
		  print "EL LOG ESTA ACTIVADO SUBSET"
		  imh = ImageReader("hist.png")
                  self.logCanvas.drawString(100,500,"Subset Histogram Created")
		  self.logCanvas.drawImage(imh,100,100)
		  self.logCanvas.showPage()
	   else:
		  print "EL LOG ESTA DESACTIVADO"


class linearRegressionWidget(QtGui.QDialog, Ui_Regression):
    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.data = rData()
        self.param = 1
        self.paramVal = 0
        self.canvasS = QtGui.QPixmap(400, 400)
        self.canvasS.fill()
        self.display.setPixmap(self.canvasS)

    def closeLinearRegression(self):
        self.reject()

    def plot(self):

        varX = []
        varY = []
        index = self.independentVariable.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index]:
                varX.append(i[self.paramVal + 1])
            del varX[0]
        else:
            varX = self.data.values[index][self.paramVal + 1]
            del varX[0]

        index = self.dependentVariable.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index]:
                varY.append(i[self.paramVal + 1])
            del varY[0]
        else:
            varY = self.data.values[index][self.paramVal + 1]
            del varY[0]

        r.assign('y', varY)
        r.assign('x', varX)
        r.assign('xlabel', str(self.independentVariable.currentText()))
        r.assign('ylabel', str(self.dependentVariable.currentText()))
        r('mslr = lm(y~x)')
        r.png("lr.png", 400, 400)
        r('plot(x, y, xlab=xlabel, ylab=ylabel, sub="Modelo de regresion simple generado")')
        r('abline(coef=mslr$coefficients, col="red")')
        r.dev_off()
        self.canvasS.load("lr.png")
        self.display.setPixmap(self.canvasS.scaled(400, 400))

        summarySLR = r('SLM_summary = summary(mslr)')
        coefficients = summarySLR['coefficients']

        self.betha0.setItem(0,0,QtGui.QTableWidgetItem(str(coefficients[0,0])))
        self.betha0.setItem(1,0,QtGui.QTableWidgetItem(str(coefficients[0,1])))
        self.betha0.setItem(2,0,QtGui.QTableWidgetItem(str(coefficients[0,2])))
        self.betha0.setItem(3,0,QtGui.QTableWidgetItem(str(coefficients[0,3])))



        self.betha1.setItem(0,0,QtGui.QTableWidgetItem(str(coefficients[1,0])))
        self.betha1.setItem(1,0,QtGui.QTableWidgetItem(str(coefficients[1,1])))
        self.betha1.setItem(2,0,QtGui.QTableWidgetItem(str(coefficients[1,2])))
        self.betha1.setItem(3,0,QtGui.QTableWidgetItem(str(coefficients[1,3])))

        self.rValue.setText(str(summarySLR['adj.r.squared']))


    def multiReg(self):

        idx1 = self.m_independent1.currentIndex()
        idx2 = self.m_independent2.currentIndex()

        if (idx1 == idx2):
            self.m_independent2.setCurrentIndex((idx2 + 1) %
                    len(self.data.variables))

        varX1 = []
        varX2 = []
        varY = []
        index = self.m_independent1.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index]:
                varX1.append(i[self.paramVal + 1])
            del varX1[0]
        else:
            varX1 = self.data.values[index][self.paramVal + 1]
            del varX1[0]

        index = self.m_independent2.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index]:
                varX2.append(i[self.paramVal + 1])
            del varX2[0]
        else:
            varX2 = self.data.values[index][self.paramVal + 1]
            del varX2[0]

        index = self.m_dependent.currentIndex()
        if (self.param == 1):
            for i in self.data.values[index]:
                varY.append(i[self.paramVal + 1])
            del varY[0]
        else:
            varY = self.data.values[index][self.paramVal + 1]
            del varY[0]

        r.assign('y', varY)
        r.assign('x1', varX1)
        r.assign('x2', varX2)
        r('multi_reg = lm(y~x1+x2)')

        summarySLR = r('SLM_summary = summary(multi_reg)')
        coefficients = summarySLR['coefficients']

        self.m_betha0.setItem(0,0,QtGui.QTableWidgetItem(str(coefficients[0,0])))
        self.m_betha0.setItem(1,0,QtGui.QTableWidgetItem(str(coefficients[0,1])))
        self.m_betha0.setItem(2,0,QtGui.QTableWidgetItem(str(coefficients[0,2])))
        self.m_betha0.setItem(3,0,QtGui.QTableWidgetItem(str(coefficients[0,3])))



        self.m_betha1.setItem(0,0,QtGui.QTableWidgetItem(str(coefficients[1,0])))
        self.m_betha1.setItem(1,0,QtGui.QTableWidgetItem(str(coefficients[1,1])))
        self.m_betha1.setItem(2,0,QtGui.QTableWidgetItem(str(coefficients[1,2])))
        self.m_betha1.setItem(3,0,QtGui.QTableWidgetItem(str(coefficients[1,3])))


        self.m_betha2.setItem(0,0,QtGui.QTableWidgetItem(str(coefficients[2,0])))
        self.m_betha2.setItem(1,0,QtGui.QTableWidgetItem(str(coefficients[2,1])))
        self.m_betha2.setItem(2,0,QtGui.QTableWidgetItem(str(coefficients[2,2])))
        self.m_betha2.setItem(3,0,QtGui.QTableWidgetItem(str(coefficients[2,3])))

        self.m_rValue.setText(str(summarySLR['adj.r.squared']))


class importLabels(QtGui.QDialog, Ui_ImportColorLabels):

    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.wb = None
        self.parameters = []

    def closeWindow(self):
        self.reject()

    def importData(self):
        self.accept()

    def browseFile(self):
        try:
            fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '.')
            self.path.setText(str(fname))
            self.wb = open_workbook(self.path.text())
            sh = self.wb.sheet_by_index(0)
            self.labelName.setText(sh.cell(0,0).value)
            for n in self.parameters:
                self.parameter.addItem(n)
        except IOError as e:
            error = QtGui.QMessageBox.warning(self, 'Warning',
                    "File doesn't exist!")


class importWidget(QtGui.QDialog, Ui_ImportDataWidget):

    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
        self.wb = None
        self.parameters = []

    def nextTab(self):
        try: 
            self.wb = open_workbook(self.path.text())
            sh = self.wb.sheet_by_index(0)
            self.variableName.setText(sh.cell(0,0).value)
            if (sh.nrows > 1):
                self.verticalCheck.setCheckState(QtCore.Qt.Checked)
            if (sh.ncols > 1):
                self.horizontalCheck.setCheckState(QtCore.Qt.Checked)
            for n in self.parameters:
                self.verticalParameter.addItem(n)
                self.horizontalParameter.addItem(n)
            if (len(self.parameters) > 1):
                self.horizontalParameter.setCurrentIndex(1)
            self.tabs.setCurrentIndex(1)
        except IOError as e:
            self.tabs.setCurrentIndex(0)
            error = QtGui.QMessageBox.warning(self, 'Warning',
                    "File doesn't exist!")

    def closeWindow(self):
        self.reject()

    def browseFile(self):
        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '.')
        self.path.setText(str(fname))
        
    def importData(self):
        self.accept()
        
    def prevTab(self):
        self.tabs.setCurrentIndex(0)

class loader(QtGui.QDialog, Ui_Dialog):
    abort = False;
    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)
    
    def rejected():
        abort = True
    
"""
    Gets the data from the sheet and saves it in rDataClass using addParam.
    The horizontal vector is given the name contained in horP
    and the vertical vector is given the name in verP.
    horP and verP are assumed to be strings
"""
def extractData(rDataClass, sheet, verP, horP):
        verValues = []
        for i in range(1, sheet.nrows):
            verValues.append(str(sheet.cell(i,0).value))

        horValues = []
        for i in range(1, sheet.ncols):
            horValues.append(str(sheet.cell(0,i).value))

        rDataClass.addParam(verP, verValues)
        rDataClass.addParam(horP, horValues)

        val = []
        for i in range(sheet.nrows):
            row = []
            for j in range(sheet.ncols):
                row.append(sheet.cell(i,j).value)
            val.append(row)

        rDataClass.values.append(val)
        
"""
    Loads all the files in data.cfg and set the default variable names
"""
def loadDefaults(mainWindow):
    dialog = loader()
    dialog.show()
    verP = "Y"
    horP = "X"
    names = 'uninitialized'
    #Load data files' file names
    try:
        with open("data.cfg", "r") as f:
            filenames = f.readlines()
    except IOError as e:
        error = QtGui.QMessageBox.warning(dialog, 'Warning',
                "Configuration file \"data.cfg\" could not be found.\n"
                +"Loading blank stage instead")
        dialog.reject()
        return
    
    #Load multiple value selection and single value selection names
    try:
        with open("axes.cfg", "r") as f:
            names = f.readlines()
        verP = names[0].strip()
        horP = names[1].strip()
    except IOError as e:
        error = QtGui.QMessageBox.warning(dialog, 'Warning',
                "Configuration file \"axes.cfg\" could not be found.\n"
                +"Using \"X\" and \"Y\" as names")
    
    dialog.progressBar.setMaximum(len(filenames))
    i = 0
    for fname in filenames:
        if(dialog.abort):
            return
        try:
            sheet = open_workbook(fname.strip()).sheet_by_index(0)
            varName = str(sheet.cell(0,0).value)
            if (mainWindow.data.variables.count(varName) == 0):
                mainWindow.data.variables.append(varName)
                extractData(mainWindow.data, sheet, "country", "year")
            else:
                error = QtGui.QMessageBox.warning(dialog, 'Warning',
                        "File \"" + fname + "\" contains variable \"" + 
                        varName + "\", which had already been defined by a file before it in \"data.cfg\"")
                
        except IOError as e:
            error = QtGui.QMessageBox.warning(dialog, 'Warning',
                    "File \"" + fname + "\" doesn't exist, and  \"data.cfg\" asks for it to be loaded")
        
        #update progress bar
        i += 1
        dialog.progressBar.setValue(i)
    
    lName = "Geographic Regions"
    pName = "country"

    wb = open_workbook("default_data/regions_subset.xls")
    sheet = wb.sheet_by_index(0)

    lValues = []
    pValues = []
    if (sheet.nrows > 2):
        for i in range(1, sheet.nrows):
            pValues.append(sheet.cell(i,0).value)
            lValues.append(sheet.cell(i,1).value)
    else:
        for i in range(1, sheet.ncols):
            pValues.append(sheet.cell(0,i).value)
            lValues.append(sheet.cell(1,i).value)

    mainWindow.data.addLabel(pName, lName, zip(pValues, lValues))


    mainWindow.updateUI()
    
    if(names != 'uninitialized'):
	    dialog.label.setText("setting up default graph")
	    try:
		mainWindow.variablesEnYTiempo.setCurrentIndex( int(names[2]) )
	    except Exception as e:
		error = QtGui.QMessageBox.warning(dialog, 'Warning',
		        "Invalid value in the third line of \"axes.cfg\"")
	    try:
		mainWindow.VariablesEnXTiempo.setCurrentIndex( int(names[3]) )
	    except Exception as e:
		error = QtGui.QMessageBox.warning(dialog, 'Warning',
		        "Invalid value in the fourth line of \"axes.cfg\"")
	    try:
		mainWindow.VariableEnRadio.setCurrentIndex( int(names[4]) )
	    except Exception as e:
		error = QtGui.QMessageBox.warning(dialog, 'Warning',
		        "Invalid value in the fifth line of \"axes.cfg\"")
	    try:
		mainWindow.diameter.setValue( double(names[5]) )
	    except Exception as e:
		error = QtGui.QMessageBox.warning(dialog, 'Warning',
		        "Invalid value in the sixth line of \"axes.cfg\"")
    #end if(names != 'uninitialized')
    
    dialog.accept()

thumbsize = 150; """The size, in pixels, of the thumbnails shown in the tooltips"""

"""
    Cambia el texto en el tooltip del widget dado a un
    summary y un histograma vector de datos obtenido
    de la columna "index" de "table"
    
    El histograma se guarda en thumbs/filename.png
"""
def updateTooltip(widget, table, index, filename):
    #get data from table
    varGraph = []
    for i in table:
        varGraph.append(i[index+1])
    
    #Generate data appearing in tooltip
    r.assign('x',varGraph)
    #r('y = as.matrix( summary(as.matrix(x)) )')
    r.png("thumbs/"+filename+".png", thumbsize, thumbsize)
    r('hist(as.matrix(x))')
    r.dev_off()
    
    widget.setToolTip(
        "<html>"
            +"<table border=\"1\">"
                +"<tr>"
                    +"<th>Min.</th>"
                    +"<th>Median</th>"
                    +"<th>Mean</th>"
                    +"<th>Max</th>"
                +"</tr>"
                +"<tr>"
                    +"<td>"+str( r('min(x)')    )+"</td>"
                    +"<td>"+str( r('median(x)') )+"</td>"
                    +"<td>"+str( r('mean(x)')   )+"</td>"
                    +"<td>"+str( r('max(x)')    )+"</td>"
                +"</tr>"
            +"</table>"
            +"<img src=\"thumbs/"+filename+".png\" alt=\"no graph\" height=\""+str(thumbsize)+"\" width=\""+str(thumbsize)+"\"/><br/>"
            #+"Your graph should be above<br/>"
        +"</html>"
        )

"""
    This is the main class for R-GUI it displays the main window.
"""
class MainWindow(QtGui.QMainWindow, Ui_RGuiMinder):
    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.setupUi(self)
        self.initUI()

    def initUI(self):

        self.data = rData()
        self.playT = playThread(0,0,"stop");
        self.varY = 0;
        self.varX = 0;
        self.varRadio = 0;
        self.charac = 0;
        self.stay0 = 0;
        self.stay1 = 0;

        """
        Actions
        """
        self.exitAction.triggered.connect(self.close)
        self.importAction.triggered.connect(self.importData)
        self.subsetAction.triggered.connect(self.subsetStadistics)

        """
        Drawing canvas parameters
        """
        self.canvasDes = QtGui.QPixmap(400, 400)
        self.canvasT = QtGui.QPixmap(400, 400)
        self.canvasT.fill()
        self.canvasTiempo.setPixmap(self.canvasT)
        self.Estadisticos.clear()

	"""
	Variable for pdf canvas log generation
	"""
	self.logCanvas = canvas.Canvas("log.pdf", pagesize=letter)
        self.logCanvas.drawString(100,500,"Automatic Generated Log for rGuiMinder Session")
	self.logCanvas.showPage()

    def SeleccionarCategorias(self):
        nombre="Daniela"
        self.canvasTiempo.setText("Hola "+nombre)

    def changeCircleSize(self, dec):
        self.diameter.setValue(dec / 100.0)
    
    
    def cambiarVariableAnalisis(self,indice):
        self.VariableAnalisis.setCurrentIndex(indice) 

    def cambiarVariableRadio(self,indice):
        self.VariableEnRadio.setCurrentIndex(indice) 

        updateTooltip(self.VariableEnRadio, self.data.values[indice][1:], self.paramValue.currentIndex(), 'r')

    def cambiarVariableX(self,indice):
        self.VariablesEnXTiempo.setCurrentIndex(indice) 
        updateTooltip(self.VariablesEnXTiempo, self.data.values[indice][1:], self.paramValue.currentIndex(), 'x')
        self.graficarBurbuja()
        

    def cambiarVariableY(self,indice):
        self.variablesEnYTiempo.setCurrentIndex(indice) 
        updateTooltip(self.variablesEnYTiempo, self.data.values[indice][1:], self.paramValue.currentIndex(), 'y')
        self.graficarBurbuja()
    
    def cambiarParametro(self, indice):
        self.scroolParam.setValue(indice)
        updateTooltip(self.VariablesEnXTiempo, self.data.values[self.VariablesEnXTiempo.currentIndex()][1:], indice, 'x')
        updateTooltip(self.variablesEnYTiempo, self.data.values[self.variablesEnYTiempo.currentIndex()][1:], indice, 'y')
        updateTooltip(self.VariableEnRadio,    self.data.values[self.VariableEnRadio.currentIndex()][1:], indice, 'r')

    def playForward(self):
        if (self.playT.isRunning()):
            self.playT.terminate()
        self.playT = playThread(self.paramValue.currentIndex(),
                                self.paramValue.count(),
                                "forward")
        self.connect( self.playT, QtCore.SIGNAL("update(int)"), self.changeFrame )
        self.playT.start()

    def stopMotion(self):
        self.playT.terminate()

    def playBackward(self):
        if (self.playT.isRunning()):
            self.playT.terminate()
        self.playT = playThread(self.paramValue.currentIndex(),
                                self.paramValue.count(),
                                "backward")
        self.connect( self.playT, QtCore.SIGNAL("update(int)"), self.changeFrame )
        self.playT.start()

    def changeFrame(self, frame):
        self.scroolParam.setValue(frame)

    def cleanData(self):
        """
	Reset data storage variables
	"""
        self.data.variables = []
        self.data.varParams = []
        self.data.parameters  = []
        self.data.paramValues = []
        self.data.labels = []
        self.data.labelsValues = []
        self.data.values = []

	"""
	Reset Ui Widgets
	"""
	self.paramCB2.clear()
	self.paramCB1.clear()
	self.paramValue.clear()
	self.paramList.clear()
	self.labelCB.clear()
	self.VariableEnRadio.clear()
	self.variablesEnYTiempo.clear()
	self.VariablesEnXTiempo.clear()
	self.Estadisticos.clear()

        

    def graficarBurbuja(self):
        self.Estadisticos.clear()
        self.varX = self.VariablesEnXTiempo.currentIndex() 
        self.varY = self.variablesEnYTiempo.currentIndex() 
        self.varRadio = self.VariableEnRadio.currentIndex() 
        self.stay1 = self.paramValue.currentIndex()

        varGraphX = []
        varGraphY = []
        varGraphRadio = []
        varColor = []
        selected = []
        countColor = 0
        
        selected = self.paramList.selectedItems()
        selectedItems = []
        
        for i in selected:
                selectedItems.append(self.paramList.row(i))
        
        print "Seleccionados"
        print selectedItems
        print len(selectedItems)

        if self.stay0 == 1:
            countColor = 0
            param = self.data.paramValues[0][:] #Aqui tengo el ano o el pais a graficar
            rowX = []
            rowY = []
            rowRadio = []
            prueba = []


            print "TODA LA VARIABLE"
            print rowX
            print "FILA"
            print self.data.values[self.varX][2]

            if len(selectedItems) == 0:
                rowX = self.data.values[self.varX][1:]
                rowY = self.data.values[self.varY][1:]
                rowRadio = self.data.values[self.varRadio][1:]
            else:
                for i in selectedItems:
                    rowX.append(self.data.values[self.varX][i+1])        
                    rowY.append(self.data.values[self.varY][i+1])        
                    rowRadio.append(self.data.values[self.varRadio][i+1])        

            for i in rowX:
                varGraphX.append(i[self.stay1+1]) #Paises o años ------> AGREGAR FOR INTERNO PARA SELECCIONAR SOLO LAS SELECCIONADAS 

            for i in rowY:
                varGraphY.append(i[self.stay1+1]) #Variable en Y
        
            for i in rowRadio:
                varGraphRadio.append(i[self.stay1+1]) #Variable en Radio

            r('legend = FALSE')
            if (self.labelCB.currentIndex() == 0):
                for i in param:            
                    varColor.append(countColor)
                    countColor += 1

            elif (self.labelCB.currentIndex() > 0):
                labIndex = self.labelCB.currentIndex()
                colorIndex  = []
                colorLabels = []
                colorInt = 1
                for i in param:            
                    for j in self.data.labelsValues[0][0]:
                        if (i == j[0]):
                            if (colorLabels.count(j[1]) == 0):
                                colorLabels.append(j[1])
                                colorIndex.append(colorInt)
                                colorInt += 1
                            else: 
                                ind = colorLabels.index(j[1])
                                colorLabels.append(j[1])
                                colorIndex.append(colorIndex[ind])
                            break
                varColor = colorIndex
                r('legend = TRUE')
                r.assign('colorLabels', list(set(colorLabels)))
                r.assign('colorIndex', list(set(colorIndex)))

            r.assign('x',varGraphX)
            r.assign('y',varGraphY)
            r.assign('radio',varGraphRadio)
            r.assign('scaleFactor', self.diameter.value())
            r.assign('bgp',varColor)
            r('g_range = range(0,xx,yy)')
            r('xx <- x')
            r('yy <- y')
            r('rr <- radio')
            r.png("graph.png", 400, 400)
            r('symbols(xx,yy,circles=rr,inches=TRUE, bg=bgp)')
            r('if (legend) legend(x=1, y=g_range[2], legend=colorLabels, pch=19, col=colorIndex)')
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))
           
            summaryx = r('as.matrix(summary(xx))')
            summaryy = r('as.matrix(summary(yy))')
            summaryradio = r('as.matrix(summary(rr))')

            for i in summaryx:
                    self.Estadisticos.addItem("X: "+str(i))
            for i in summaryy:
                    self.Estadisticos.addItem("Y: "+str(i))
            for i in summaryradio:
                    self.Estadisticos.addItem("R: "+str(i))

	    """
		Save Log file
	    """

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   im = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Bubble Chart Created")
		   self.logCanvas.drawImage(im,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"




        else: ##LO HACE BIEN
            param = self.data.paramValues[1][:] #Aqui tengo el ano o el pais a graficar
            varx = self.data.values[self.varX][self.stay1+1]
            vary = self.data.values[self.varY][self.stay1+1]
            varradio = self.data.values[self.varRadio][self.stay1+1]


            if len(selectedItems) == 0:
                    varGraphX = varx[1:]
                    varGraphY = vary[1:]
                    varGraphRadio = varradio[1:]
            else:
                    for i in selectedItems:
                                varGraphX.append(varx[i+1])
                                varGraphY.append(vary[i+1])
                                varGraphRadio.append(varradio[i+1])
            
            print "PAIS"
            print varGraphX
            print varGraphY
            print varGraphRadio
            
            r.assign('x',varGraphX)
            r.assign('y',varGraphY)
            r.assign('radio',varGraphRadio)
            r.assign('bgp',param)
            r('xx <- x')
            r('yy <- y')
            r.assign('scaleFactor', self.diameter.value())
            r('rr <- radio')
            r.png("graph.png", 400, 400)
            r('symbols(xx,yy,circles=rr,inches=TRUE,bg=bgp)')    
            r('if (legend) legend(x=1, y=g_range[2], legend=colorLabels, pch=19, col=colorIndex)')
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))

            summaryx = r('as.matrix(summary(xx))')
            summaryy = r('as.matrix(summary(yy))')
            summaryradio = r('as.matrix(summary(rr))')


            for i in summaryx:
                    self.Estadisticos.addItem("X: "+str(i))
            for i in summaryy:
                    self.Estadisticos.addItem("Y: "+str(i))
            for i in summaryradio:
                    self.Estadisticos.addItem("R: "+str(i))

	    if self.saveLog.isChecked():
		   print "EL LOG ESTA ACTIVADO"
		   ima = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Bubble Chart Created")
		   self.logCanvas.drawImage(ima,100,100)
		   self.logCanvas.showPage()

	    else:
		   print "EL LOG ESTA DESACTIVADO"


    def graficarCaja(self):
        self.varX = self.VariableAnalisis.currentIndex()         
        self.Estadisticos.clear()
        self.stay1 = self.paramValue.currentIndex()

        varGraphX = []
        varGraphY = []
        varGraphRadio = []
        varColor = []
        selected = []
        countColor = 0
        
        selected = self.paramList.selectedItems()
        selectedItems = []
        
        for i in selected:
                selectedItems.append(self.paramList.row(i))
        
        print "Seleccionados"
        print selectedItems
        print len(selectedItems)

        if self.stay0 == 1:
            countColor = 0
            param = self.data.paramValues[0][:] #Aqui tengo el ano o el pais a graficar
            rowX = []
            rowY = []
            rowRadio = []
            prueba = []


            print "TODA LA VARIABLE"
            print rowX
            print "FILA"
            print self.data.values[self.varX][2]

            if len(selectedItems) == 0:
                            rowX = self.data.values[self.varX][1:]
            else:
                            for i in selectedItems:
                                rowX.append(self.data.values[self.varX][i+1])        

            for i in rowX:
                        varGraphX.append(i[self.stay1+1]) #Paises o años ------> AGREGAR FOR INTERNO PARA SELECCIONAR SOLO LAS SELECCIONADAS 

            for i in param:            
                varColor.append(countColor)
                countColor = countColor+1

            print "ANO"    
            print "VAR X "
            print self.varX
            print "VAR Y "
            print self.varY
            print "VAR RADIO "
            print self.varRadio
            print varGraphX

            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            r.png("graph.png", 400, 400)
            r('boxplot(xx)')    
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))
           
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))

	    """
		Save Log file
	    """

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   imb = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Box Plot Created")
		   self.logCanvas.drawImage(imb,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"



        else: ##LO HACE BIEN
            param = self.data.paramValues[1][:] #Aqui tengo el ano o el pais a graficar
            varx = self.data.values[self.varX][self.stay1+1]


            if len(selectedItems) == 0:
                    varGraphX = varx[1:]
            else:
                    for i in selectedItems:
                                varGraphX.append(varx[i+1])
            
            print "PAIS"
            print varGraphX
            
            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            r.png("graph.png", 400, 400)
            r('boxplot(xx)')    
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))            
     
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   imbx = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Box Plot Created")
		   self.logCanvas.drawImage(imbx,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"




    def graficarHistograma(self):
        self.varX = self.VariableAnalisis.currentIndex()         
        self.Estadisticos.clear()
        self.stay1 = self.paramValue.currentIndex()

        varGraphX = []
        varGraphY = []
        varGraphRadio = []
        varColor = []
        selected = []
        countColor = 0
        
        selected = self.paramList.selectedItems()
        selectedItems = []
        
        for i in selected:
                selectedItems.append(self.paramList.row(i))
        
        print "Seleccionados"
        print selectedItems
        print len(selectedItems)

        if self.stay0 == 1:
            countColor = 0
            param = self.data.paramValues[0][:] #Aqui tengo el ano o el pais a graficar
            rowX = []
            rowY = []
            rowRadio = []
            prueba = []


            print "TODA LA VARIABLE"
            print rowX
            print "FILA"
            print self.data.values[self.varX][2]

            if len(selectedItems) == 0:
                            rowX = self.data.values[self.varX][1:]
            else:
                            for i in selectedItems:
                                rowX.append(self.data.values[self.varX][i+1])        

            for i in rowX:
                        varGraphX.append(i[self.stay1+1]) #Paises o años ------> AGREGAR FOR INTERNO PARA SELECCIONAR SOLO LAS SELECCIONADAS 

            for i in param:            
                varColor.append(countColor)
                countColor = countColor+1

            print "ANO"    
            print "VAR X "
            print self.varX
            print "VAR Y "
            print self.varY
            print "VAR RADIO "
            print self.varRadio
            print varGraphX

            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            r.png("graph.png", 400, 400)
            r('hist(xx)')    
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))
           
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   imh = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Histogram Created")
		   self.logCanvas.drawImage(imh,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"



        else: ##LO HACE BIEN
            param = self.data.paramValues[1][:] #Aqui tengo el ano o el pais a graficar
            varx = self.data.values[self.varX][self.stay1+1]


            if len(selectedItems) == 0:
                    varGraphX = varx[1:]
            else:
                    for i in selectedItems:
                                varGraphX.append(varx[i+1])
            
            print "PAIS"
            print varGraphX
            
            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            r.png("graph.png", 400, 400)
            r('hist(xx)')    
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))            
     
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   imhx = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Histogram Created")
		   self.logCanvas.drawImage(imhx,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"


    def graficarPuntos(self):
        self.varX = self.VariableAnalisis.currentIndex()         
        self.Estadisticos.clear()
        self.stay1 = self.paramValue.currentIndex()

        varGraphX = []
        varGraphY = []
        varGraphRadio = []
        varColor = []
        selected = []
        countColor = 0
        
        selected = self.paramList.selectedItems()
        selectedItems = []
        
        for i in selected:
                selectedItems.append(self.paramList.row(i))
        
        print "Seleccionados"
        print selectedItems
        print len(selectedItems)

        if self.stay0 == 1:
            countColor = 0
            param = self.data.paramValues[0][:] #Aqui tengo el ano o el pais a graficar
            rowX = []
            rowY = []
            rowRadio = []
            prueba = []


            print "TODA LA VARIABLE"
            print rowX
            print "FILA"
            print self.data.values[self.varX][2]

            if len(selectedItems) == 0:
                            rowX = self.data.values[self.varX][1:]
            else:
                            for i in selectedItems:
                                rowX.append(self.data.values[self.varX][i+1])        

            for i in rowX:
                        varGraphX.append(i[self.stay1+1]) #Paises o años ------> AGREGAR FOR INTERNO PARA SELECCIONAR SOLO LAS SELECCIONADAS 

            for i in param:            
                varColor.append(countColor)
                countColor = countColor+1

            print "ANO"    
            print "VAR X "
            print self.varX
            print "VAR Y "
            print self.varY
            print "VAR RADIO "
            print self.varRadio
            print varGraphX

            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            r.png("graph.png", 400, 400)
            r('plot(xx)')    
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))
           
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   imp = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Plot Created")
		   self.logCanvas.drawImage(imp,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"



        else: ##LO HACE BIEN
            param = self.data.paramValues[1][:] #Aqui tengo el ano o el pais a graficar
            varx = self.data.values[self.varX][self.stay1+1]


            if len(selectedItems) == 0:
                    varGraphX = varx[1:]
            else:
                    for i in selectedItems:
                                varGraphX.append(varx[i+1])
            
            print "PAIS"
            print varGraphX
            
            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            r.png("graph.png", 400, 400)
            r('plot(xx)')    
            r.dev_off()
            self.canvasT.load("graph.png")
            self.canvasTiempo.setPixmap(self.canvasT.scaled(400, 400))            
     
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))

	    if self.saveLog.isChecked() :
		   print "EL LOG ESTA ACTIVADO"
		   impx = ImageReader("graph.png")
                   self.logCanvas.drawString(100,500,"Plot Created")
		   self.logCanvas.drawImage(impx,100,100)
		   self.logCanvas.showPage()
	    else:
		   print "EL LOG ESTA DESACTIVADO"



    def subsetStadistics(self):

        subSta = subsetWidget()

        subSta.data = self.data
        subSta.logCanvas = self.logCanvas
        subSta.logBool = self.saveLog.isChecked()

        for i in self.data.variables:
            subSta.categorical.addItem(i)
            subSta.noCategorical.addItem(i)

        subSta.param = self.paramCB2.currentIndex()
        subSta.paramVal = self.paramValue.currentIndex()

        subSta.splitVariable()
        subSta.splitVariable2()

        subSta.exec_()

    def linearRegression(self):

        lr = linearRegressionWidget()
        lr.data = self.data

        for i in self.data.variables:
            lr.independentVariable.addItem(i)
            lr.dependentVariable.addItem(i)
            lr.m_dependent.addItem(i)
            lr.m_independent1.addItem(i)
            lr.m_independent2.addItem(i)

        lr.param = self.paramCB2.currentIndex()
        lr.paramVal = self.paramValue.currentIndex()
        lr.plot()
        lr.multiReg()
        lr.exec_()

    def importColorLabels(self):
        impCL = importLabels()

        if (self.data.varParams == []):
            impCL.parameters = [ "Y" , "X" ]
        else:
            impCL.parameters = self.data.parameters
        
        if impCL.exec_():

            lName = str(impCL.labelName.text())
            pName = str(impCL.parameter.currentText())

            sheet = impCL.wb.sheet_by_index(0)

            lValues = []
            pValues = []
            if (sheet.nrows > 2):
                for i in range(1, sheet.nrows):
                    pValues.append(sheet.cell(i,0).value)
                    lValues.append(sheet.cell(i,1).value)
            else:
                for i in range(1, sheet.ncols):
                    pValues.append(sheet.cell(0,i).value)
                    lValues.append(sheet.cell(1,i).value)

            self.data.addLabel(pName, lName, zip(pValues, lValues))
            self.updateUI()

    def importData(self):

        imp = importWidget()

        if (self.data.varParams == []):
            imp.parameters = [ "Y" , "X" ]
        else:
            imp.parameters = self.data.parameters

        if imp.exec_():

            if (self.data.variables.count(str(imp.variableName.text())) == 0):
                self.data.variables.append(str(imp.variableName.text()))

                verP = str(imp.verticalParameter.currentText())
                horP = str(imp.horizontalParameter.currentText())
                self.data.varParams.append([ verP, horP ])

                sheet = imp.wb.sheet_by_index(0)

                extractData(self.data, sheet, verP, horP)

                self.updateUI()

            else:

                error = QtGui.QMessageBox.warning(self, 'Warning',
                        "Variable name already exist")

    def obtenerEstadisticos(self):
        self.varX = self.VariableAnalisis.currentIndex()         
        self.Estadisticos.clear()
        self.stay1 = self.paramValue.currentIndex()

        varGraphX = []
        varGraphY = []
        varGraphRadio = []
        varColor = []
        selected = []
        countColor = 0
        
        selected = self.paramList.selectedItems()
        selectedItems = []
        
        for i in selected:
                selectedItems.append(self.paramList.row(i))
        
        print "Seleccionados"
        print selectedItems
        print len(selectedItems)

        if self.stay0 == 1:
            countColor = 0
            param = self.data.paramValues[0][:] #Aqui tengo el ano o el pais a graficar
            rowX = []
            rowY = []
            rowRadio = []
            prueba = []


            print "TODA LA VARIABLE"
            print rowX
            print "FILA"
            print self.data.values[self.varX][2]

            if len(selectedItems) == 0:
                            rowX = self.data.values[self.varX][1:]
            else:
                            for i in selectedItems:
                                rowX.append(self.data.values[self.varX][i+1])        

            for i in rowX:
                        varGraphX.append(i[self.stay1+1]) #Paises o años ------> AGREGAR FOR INTERNO PARA SELECCIONAR SOLO LAS SELECCIONADAS 

            for i in param:            
                varColor.append(countColor)
                countColor = countColor+1

            print "ANO"    
            print "VAR X "
            print self.varX
            print "VAR Y "
            print self.varY
            print "VAR RADIO "
            print self.varRadio
            print varGraphX

            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            summaryx = r('as.matrix(summary(xx))')


            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))


        else: ##LO HACE BIEN
            param = self.data.paramValues[1][:] #Aqui tengo el ano o el pais a graficar
            varx = self.data.values[self.varX][self.stay1+1]


            if len(selectedItems) == 0:
                    varGraphX = varx[1:]
            else:
                    for i in selectedItems:
                                varGraphX.append(varx[i+1])
            
            print "PAIS"
            print varGraphX

            r.assign('x',varGraphX)
            r('xx <- as.matrix(x)')
            summaryx = r('as.matrix(summary(xx))')



            for i in summaryx:
                    self.Estadisticos.addItem("VAR: "+str(i))



    
    def cambiaRadioCirculo(self):
        nombre="Daniela"
        self.canvasTiempo.setText("Hola "+nombre)

    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
                "Are you sure to quit?", QtGui.QMessageBox.Yes | 
                QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            self.logCanvas.showPage()
            self.logCanvas.save()
            event.accept()
        else:
            event.ignore()

    def updateUI(self):
        index = self.paramCB1.currentIndex()
        self.paramCB1.clear()
        for i in self.data.parameters:
            self.paramCB1.addItem(i)

        if (index != -1):
            self.paramCB1.setCurrentIndex(index)
        else:
            self.paramCB1.setCurrentIndex(0)

        index2 = self.paramCB2.currentIndex()
        self.paramCB2.clear()
        for i in self.data.parameters:
            self.paramCB2.addItem(i)

        if (index2 != -1):
            self.paramCB2.setCurrentIndex(index)
        else:
            self.paramCB2.setCurrentIndex(1)
       
        indexL = self.paramCB1.currentIndex()
        self.labelCB.clear()
        self.labelCB.addItem(str(self.paramCB1.currentText()))
        for i in self.data.labels[indexL]:
            self.labelCB.addItem(i)

        index3 = self.VariablesEnXTiempo.currentIndex() 
        self.VariablesEnXTiempo.clear()

        for i in self.data.variables:
            self.VariablesEnXTiempo.addItem(i)
        if(index3 != -1):
           self.VariablesEnXTiempo.setCurrentIndex(index3)
        else:
           self.VariablesEnXTiempo.setCurrentIndex(1)

        index3 = self.variablesEnYTiempo.currentIndex() 
        self.variablesEnYTiempo.clear()

        for i in self.data.variables:
            self.variablesEnYTiempo.addItem(i)
        if(index3 != -1):
           self.variablesEnYTiempo.setCurrentIndex(index3)
        else:
           self.variablesEnYTiempo.setCurrentIndex(1)

        index3 = self.VariableEnRadio.currentIndex() 
        self.VariableEnRadio.clear()

        for i in self.data.variables:
            self.VariableEnRadio.addItem(i)
        if(index3 != -1):
           self.VariableEnRadio.setCurrentIndex(index3)
        else:
           self.VariableEnRadio.setCurrentIndex(1)

        index3 = self.VariableAnalisis.currentIndex() 
        self.VariableAnalisis.clear()

        for i in self.data.variables:
            self.VariableAnalisis.addItem(i)
        if(index3 != -1):
           self.VariableAnalisis.setCurrentIndex(index3)
        else:
           self.VariableAnalisis.setCurrentIndex(1)



        
    def updateList(self, index):
        self.paramList.clear()
        for i in self.data.paramValues[index]:
            if (type(i).__name__=='float'):
                self.paramList.addItem(str(i))
            else:
                self.paramList.addItem(i)

        if (self.paramCB2.currentIndex() == self.paramCB1.currentIndex()):
            self.paramCB2.setCurrentIndex((index + 1) % 2)
    
        indexL = self.paramCB1.currentIndex()
        self.labelCB.clear()
        self.labelCB.addItem(str(self.paramCB1.currentText()))
        for i in self.data.labels[indexL]:
            self.labelCB.addItem(i)


    def updateCB(self, index):
        self.paramValue.clear()
        for i in self.data.paramValues[index]:
            if (type(i).__name__=='float'):
                self.paramValue.addItem(str(i))
            else:
                self.paramValue.addItem(i)
        self.scroolParam.setMaximum(len(self.data.paramValues[index]) - 1)
        self.stay0=index

        if (self.paramCB2.currentIndex() == self.paramCB1.currentIndex()):
            self.paramCB1.setCurrentIndex((index + 1) % 2)
        
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MainWindow()
    myapp.show()
    loadDefaults(myapp)
    myapp.graficarBurbuja()
    sys.exit(app.exec_())
